<template>
  <el-dialog :append-to-body='true' :visible.sync="visible" width="660px" title="断奶" :close-on-click-modal="true" :close-on-press-escape="true">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'">
      <el-row v-if="dataForm.id == undefined">
        <el-col :span="12">
          <el-form-item size='small' label="母猪耳号" prop="earmark">
            <!--<pig-tree :props="props"
              :options="optionData"
              :value="valueId"
              :filter="0"
              :clearable="isClearable"
              :accordion="isAccordion"
              @getValue="getValue($event)"></pig-tree>-->
            <Earmark gender="1" placeholder="母猪耳号" v-model="dataForm.sow" ref="refEarmark"></Earmark>
            <!-- <el-autocomplete v-model="dataForm.earmark" :fetch-suggestions="queryPigAsync" placeholder="母猪耳号"></el-autocomplete> -->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item size='small' label="断奶日期" prop="weanDate">
            <el-date-picker
              v-model="dataForm.weanDate"
              align="right"
              type="date"
              placeholder="断奶日期"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="断奶头数" prop="mounts">
            <el-input v-model="dataForm.mounts" placeholder="断奶头数"><i slot="suffix" style="font-style:normal;margin-right: 10px;">{{weanCount}}头</i></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="转入猪舍" prop="toHouseId">
            <el-select v-model="dataForm.toHouseId" @change="house_change" placeholder="请选择">
              <el-option
                  v-for="(house, house_id) in houses"
                  :key="house_id"
                  :label="house.name"
                  :value="house_id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="转入猪舍栏位" prop="toGrid">
            <el-select size='mini' style="width: 90px" v-model="dataForm.toGrid.row" placeholder="行">
              <el-option
                v-for="item in rows"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-select size='mini' style="width: 90px" v-model="dataForm.toGrid.column" placeholder="列">
              <el-option
                v-for="item in columns"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item size='small' label="背膘厚度" prop="backfat">
            <el-input v-model="dataForm.backfat" placeholder="背膘厚度"><i slot="suffix" style="font-style:normal;margin-right: 10px;">mm</i></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item size='small' label="操作人" prop="operator">
            <UserSelect v-model="dataForm.operator"></UserSelect>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item size='small' label="备注" prop="remark">
        <el-input type="textarea" rows="2" v-model="dataForm.remark" placeholder="备注"></el-input>
      </el-form-item>
    </el-form>
    <Grid v-if="dataForm.toHouseId" v-on:gridSelect="gridSelect" :pig="dataForm" :house_id="dataForm.toHouseId"></Grid>
    <template slot="footer">
      <el-divider></el-divider>
      <el-row>
        <el-col :span="4">
          <el-checkbox label="连续录入" v-model="continues"></el-checkbox>
        </el-col>
        <el-col :span="20">
          <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
          <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>/* eslint-disable */
import debounce from 'lodash/debounce'
export default {
  data () {
    return {
      weanCount: 0,
      rows: [],
      columns: [],
      visible: false,
      continues: true,
      houses: {},
      pigs: [],
      dataForm: {
        id: '',
        pigId: '',
        earmark: '',
        weanDate: '',
        mounts: '',
        toHouseId: '',
        toGrid: {row: '', column: ''},
        operator: '',
        remark: '',
        backfat: '',
        sow: {}
      },
      pickerOptions: {
        disabledDate: (time) => {
            var year1=new Date(time).getFullYear();
				    var year2=new Date().getFullYear();
            return time.getTime() > Date.now() || (year2-year1 >= 5);
        }
      }
    }
  },
  computed: {
    dataRule () {
      return {
        pigId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        type: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    gridSelect(grid) {
      console.table(grid)
      this.dataForm.toGrid.row = grid.row
      this.dataForm.toGrid.column = grid.column
      this.$forceUpdate()
    },
    init () {
      let that = this
      this.visible = true
      this.$nextTick(() => {
        this.$refs.refEarmark.$on('earmarkChange', this.getWeanCount)
        if (!this.dataForm.id) {
          this.$refs['dataForm'].resetFields()
          that.$forceUpdate()
        }
        this.getHouses()
      })
    },
    inBtnClick () {
      this.visible = false
      this.$emit("uploadModal");
    },
    getWeanCount () {
      let that = this;
      that.pigs = [];
      if(this.dataForm.sow) {
        this.$http.get(`/stock/piggrowth/getWeamMounts/${this.dataForm.sow.id}`).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          that.weanCount = res.data
          that.dataForm.mounts = that.weanCount
          this.$forceUpdate()
        }).catch(() => {}) 
      }   
    },
    getPigs () {
      let that = this;
      that.pigs = [];
      this.$http.get(`/stock/pig/getAllEarMarks`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        res.data.forEach(function(earmark){
          that.pigs.push({value: earmark});
        });
        this.$forceUpdate()
      }).catch(() => {})   
    },
    queryPigAsync(queryString, cb) {
      var pigs = this.pigs;
      var results = queryString ? pigs.filter(this.createStateFilter(queryString)) : pigs;
      cb(results);
    },
    createStateFilter(queryString) {
      return (earmark) => {
        let equal = (earmark.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1);
        return equal;
      };
    },
    getHouses () {
      let that = this;
      this.$http.get(`/basic/house/all`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        res.data.forEach(function(house){
          that.houses[house.id] = house;
        });
        that.$forceUpdate()
      }).catch(() => {})
    },
    house_change() {
      let house = this.houses[this.dataForm.toHouseId]
      this.rows = []
      this.columns = []
      for (let i=0; i<house.rows; ++i) {
        this.rows.push({
          value: i+1,
          label: i+1+'行'
        })
      }
      for (let i=0; i<house.columns; ++i) {
        this.columns.push({
          value: i+1,
          label: i+1+'列'
        })
      }
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/stock/pig/out/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      if (this.dataForm.sow) {
        this.dataForm.earmark = this.dataForm.sow.earmark;
        this.dataForm.pigId = this.dataForm.sow.id;
      }
      if (this.dataForm.id) {
        this.dataForm['weanDate'] = this.dataForm['weanDate'] + ' 00:00:00';
      }
      let that = this;
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        that.dataForm.toGrid = that.dataForm.toGrid.row + '-' + that.dataForm.toGrid.column;
        let method = this.dataForm.id ? 'put' : 'post';
        that.$http[method]('/stock/pig/wean/', that.dataForm).then(({ data: res }) => {
          that.dataForm.toGrid = {row: '', column: ''};
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          that.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              if(!this.continues) {
                that.visible = false
              } else {
                for(let key in this.dataForm) {
                  that.dataForm[key] = '';
                }
              }
              that.$emit('refreshData')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
<style scoped>
    .el-input, .el-select {
      width: 180px;
    }

    .el-textarea {
      width: 460px;
    }
</style>
